package com.mitac.mcd.cs.mobiletracking.socketserver;

import java.beans.PropertyVetoException;
import java.io.*;
import java.net.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;


import net.rubyeye.xmemcached.exception.MemcachedException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.mitac.mcd.cs.mobiletracking.socketserver.bean.NotificationMarkBean;
import com.mitac.mcd.cs.mobiletracking.socketserver.bean.TcpSocketBean;
import com.mitac.mcd.cs.mobiletracking.socketserver.util.BusinessUtil;
import com.mitac.mcd.cs.mobiletracking.socketserver.util.ClientCMDEnum;
import com.mitac.mcd.cs.mobiletracking.socketserver.util.DBConnection;
import com.mitac.mcd.cs.mobiletracking.socketserver.util.DeviceConnectMode;
import com.mitac.mcd.cs.mobiletracking.socketserver.util.Formatter;
import com.mitac.mcd.cs.mobiletracking.socketserver.util.MemcacheUtil;
import com.mitac.mcd.cs.mobiletracking.socketserver.util.RandomId;

/**
 * 服务器端逻辑线程
 */
public class MobileServerThread extends Thread {
    MobileServer server;
    Socket socket;
    
    public int gpsUploadIntervalTime;
    java.sql.Connection db = null;
    public TcpSocketBean tcb = null;
    String id = null;
    public String uuid = null;
    public String ref_uuid = null;
    public String auttoken = null;
    public DeviceConnectMode mode = DeviceConnectMode.beTracked;
    public String[] groupId = null;
    public String[] taskId = null;
    public int user_id = -1;
    public int ref_userId  = -1;
    public int deviceType = -1;
    public int interval = -1;
    public String clientAddress = null;
    String [] coordinates = null;
    double speed;
    String date = null;
    int type=-1;
    int status = 1;//1 means success, 0 means error
    int count = 0;
    String[] intervalBufferArray = null;
    public String exceptionPropCode = null;
    private boolean _run = true;
    private boolean autFlag = false;
    private boolean isAut = false;
    public static String PREFIX_LOCK = "LOCK_";
    public static long MEMCACHE_LOCKKEY_EXPIRATION;
    public PrintStream PS = null;
    private Calendar autStartTime = null;
    private Calendar autFinishTime = null;
    public static boolean sql_error = true;
    public static boolean mem_error = true;
    public boolean isExeCloseSocketDone = false;
    
    public MobileServerThread(MobileServer server,Socket socket) {
        this.server = server;
        this.socket = socket;
        try {
			PS = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
        //初始化缓存interval buffer的数组
        intervalBufferArray = new String[MobileServer.tcpSocketGpsuploadExpPacketCount];
        clientAddress = socket.getInetAddress().getHostAddress();
        MEMCACHE_LOCKKEY_EXPIRATION = MobileServer.memcacheLockKeyWaitTime*MobileServer.memcacheLockKeyLockCounts*2;
        this.start();
    }
    
    public void run() {
        BusinessUtil.aLogger.info("新开一个线程:"+socket);
        BufferedReader inBr = null;
        String str = null;
        InputStream Is = null;
        /***开始记录新线程的相关信息到TcpSocketBean中用于health check***/
        tcb = new TcpSocketBean();
        id = (new Date()).getTime()+RandomId.getRandomString(6);
        tcb.setId(id);
        tcb.setStartTime(new Date());
        /***完成记录新线程的相关信息到TcpSocketBean中用于health check***/
        HealthCheck hc = new HealthCheck(this);
        BusinessUtil.aLogger.info("启动health check线程完成...");
        
        try {
        	Is = socket.getInputStream();
            inBr = new BufferedReader(new InputStreamReader(Is,MobileServer.ENCODING));
            while(_run){
                str = inBr.readLine();
                BusinessUtil.aLogger.info("接收到client发送的讯息为:"+str);
                JSONObject jsonObject = null;
                if(str!=null&&!"".equals(str)){
                	try{
                		jsonObject = JSONObject.fromObject(str);
                	}catch(Exception e1){//上传数据格式不是规范的json格式
                		e1.printStackTrace();
                		//log to db
                		exceptionPropCode = "E008";
                		status = 0;
            			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, exceptionPropCode,""+e1);
            			BusinessUtil.sendMessage("aut",status,exceptionPropCode,PS);
            			break;
                	}
                	
                    //request为验证
                    if (BusinessUtil.judge(jsonObject).equals(ClientCMDEnum.CMD.aut)){
                    	BusinessUtil.aLogger.info("Request Type==="+ClientCMDEnum.CMD.aut);
                    	//set aut start time
                    	autStartTime = Calendar.getInstance();
                    	//在TcpSocketList中设置已经接收到aut信息的标记
                        tcb.setAutFlag(true);
                    	try{
                    		uuid = (String) jsonObject.get("uid");
                    		auttoken = (String) jsonObject.get("auttoken");
                            deviceType = Integer.parseInt(jsonObject.get("dev_type").toString());
                            interval = Integer.parseInt(jsonObject.get("interval").toString());
                    	}catch(Exception e2){//上传数据参数不符合要求
                    		e2.printStackTrace();
                    		//log to db
                    		exceptionPropCode = "E009";
                    		status = 0;
                			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, exceptionPropCode,""+e2);
                			BusinessUtil.sendMessage("aut",status,exceptionPropCode,PS);
                			break;
                    	}
                    	boolean isUnvalidatedPara = false;
                    	if (null==uuid||uuid.equals("")) isUnvalidatedPara = true;
                        if (isUnvalidatedPara){
                        	//log to db
                        	exceptionPropCode = "E009";
                        	status = 0;
                			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, exceptionPropCode,null);
                			BusinessUtil.sendMessage("aut",status,exceptionPropCode,PS);
                			break;
                        }
                    	//check max connection count
                        if (MobileServer.outputStreams.size()>=MobileServer.tcpSokcetMaxConnection){
                        	BusinessUtil.aLogger.info("已经超过server最大连接数，必须中断此连接...");
                        	//log to db
                        	exceptionPropCode = "E007";
                        	status = 0;
							BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, exceptionPropCode,null);
							BusinessUtil.sendMessage("aut",status,exceptionPropCode,PS);
                        	break;
                        }
                        
                        try{
                            
                            //如果有UUID则返回对应的group id，一个UUID可能对应多个group id,和user_id
                            BusinessUtil.aLogger.info("开始根据uuid查询device在系统中是否有注册...");
                            autByDB();
                            BusinessUtil.aLogger.info("结束根据uuid查询device在系统中是否有注册...");
                            //end check UUID
                            
                            //没有返回groupId和userId，没有通过验证
                            if (this.autFlag){
                            	String note = "没有返回groupId和userId，没有通过验证";
                            	status = 0;
                            	BusinessUtil.aLogger.info(note);
                            	//log to db
                            	exceptionPropCode = "E010";
                            	status = 0;
    							BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, exceptionPropCode,note);
    							BusinessUtil.sendMessage("aut",status,exceptionPropCode,PS);
    							break;
                            }else{
                            	//begin check Group
                            	if(groupId!=null) {
                            		if(MobileServer.uuidGroupList.containsKey(this.uuid)){
                                		MobileServer.uuidGroupList.remove(this.uuid);
                                	}
                            		MobileServer.uuidGroupList.put(this.uuid, groupId);
                            		checkGroup(uuid,this.user_id,groupId,mode);
                            	}
                                //end check Group
                                //begin check Task
                                if(taskId!=null) {
                                	if(MobileServer.uuidTaskList.containsKey(this.uuid)){
                                		MobileServer.uuidTaskList.remove(this.uuid);
                                	}
                                	MobileServer.uuidTaskList.put(this.uuid, taskId);
                                	checkTask(uuid,this.user_id,taskId,mode);
                                }
                                
                                //end check Task
                            }
                        }catch(Exception ex){
                            ex.printStackTrace();
                            status = 0;
                        }
                        
                        //authenticate successfully,check and put health check thread into list
                        if(MobileServer.healthCheckList.containsKey(uuid)){//uuid health check thread has already exists
                        	HealthCheck _hc = MobileServer.healthCheckList.get(uuid);
                        	//向被覆盖的thread发送aut error讯息
                        	if (MobileServer.outputStreams.containsKey(uuid)){
                        		BusinessUtil.sendMessage("aut",0,"E014",MobileServer.outputStreams.get(uuid));
                        	}
                        	_hc.breakConnectionDone();//终止前uuid对应的MobileServerThread thread
                        	_hc.stopThread();//终止前uuid对应的health check thread
                        	MobileServer.healthCheckList.remove(uuid);//在healthCheckList中删除前uuid对应的object
                        	BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E014",null);
                        }
                        MobileServer.healthCheckList.put(uuid, hc);
                        //authenticate successfully,put outputStream in Hashtable
                        if (status==1){
                        	BusinessUtil.addConnection(uuid,PS);
                        }
                        //put uuid and userid
                        if(MobileServer.uuidUseridList.containsKey(uuid)){
                        	MobileServer.uuidUseridList.remove(uuid);
                        }
                        MobileServer.uuidUseridList.put(uuid, String.valueOf(this.user_id));
                        //put userid and uuid
                        if(MobileServer.useridUuidList.containsKey(this.user_id)){
                        	MobileServer.useridUuidList.remove(this.user_id);
                        }
                        MobileServer.useridUuidList.put(String.valueOf(this.user_id), uuid);
                        //设定aut成功标记
                        isAut = true;
                        //log online client info
                        BusinessUtil.logOnlineClient(uuid, user_id, MobileServer.SERVER_ID, null);
                        //set aut finish time
                        autFinishTime = Calendar.getInstance();
                        BusinessUtil.logAut(autStartTime, autFinishTime, uuid, user_id, server.IP,null);
                        //BusinessUtil.logOnlineClient(uuid, MobileServer.SERVER_SN,MobileServer.IP, MobileServer.PORT, null);
                        //设定aut成功后标记时间
                        tcb.setFinishAutTime(new Date());
                        //check online client count threshold
                        checkOnlineCountThreshold();
                        //计算client device上传数据间隔时间限制
                        gpsUploadIntervalTime = MobileServer.tcpSocektGpsuploadHealthPolicyCount*MobileServer.coordinatesBufferLength*interval;
                        //begin return json object
                        BusinessUtil.sendMessage("aut",status,exceptionPropCode,PS);
                        //end return json object
                        
                    }else if (BusinessUtil.judge(jsonObject).equals(ClientCMDEnum.CMD.gpsupload)){
                        BusinessUtil.aLogger.info("Request Type==="+ClientCMDEnum.CMD.gpsupload);
                        
                    	if (!isAut){//没有通过authentication
                    		BusinessUtil.aLogger.info("本次gps upload之前没有通过authentication，退出线程...");
                    		break;
                    	}
                    	try{
                            uuid = (String) jsonObject.get("uid");
                            
                            JSONArray array = JSONArray.fromObject(jsonObject.get("coordinates").toString());
                            Object [] objectArray = array.toArray();
                            JSONObject jsonObject0 = JSONObject.fromObject(objectArray[0]);
                            JSONObject jsonObject1 = JSONObject.fromObject(objectArray[1]);
                            JSONObject jsonObject2 = JSONObject.fromObject(objectArray[2]);
                            coordinates = new String[3];
                            coordinates[0] = jsonObject0.get("lat").toString();
                            coordinates[1] = jsonObject1.get("lon").toString();
                            coordinates[2] = jsonObject2.get("height").toString();
                            
                            speed = Double.parseDouble(jsonObject.get("speed").toString());
                            //date = (String) jsonObject.get("date");
                            date = Formatter.sdf.format(new Date());
                    	}catch(Exception ex){
                    		exceptionPropCode = "E009";
                			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, exceptionPropCode,""+ex);
                        	BusinessUtil.aLogger.info(uuid+"gpsupload command解析出错:"+ex);
                        	continue;
                        }
                    	boolean upload_flag = checkAndUploadCoordinates(uuid,user_id,deviceType,coordinates,speed,date);
                        if (!upload_flag){
                        	break;
                        }
                        //设置本次接收数据时间标记
                        tcb.setEachRecieveDataTime(new Date());
                        
                        /*
                         * 测试在执行流程完成之前client就断开是否会影响到server业务逻辑的执行，结论是不会
                        SocketAddress socketaddress = new InetSocketAddress("192.168.1.104",8000);
                        Socket t_socket = null;
                        t_socket = new Socket();
                        t_socket.connect(socketaddress,50*1000);
        	    		OutputStream Oss = null;
        				PrintStream PSs = null;
        				if (!t_socket.isClosed()){
        					Oss = t_socket.getOutputStream();
        					PSs = new PrintStream(Oss);
        	    		}
        				PSs.println("sss");
        	    		BusinessUtil.aLogger.info("test data send OK");
        	    		InputStream Iss = null;
        	    		BufferedReader inBrs = null;
        	    		String strs = null;
        	    		boolean testflag = true;
        	    		while(testflag){
        	    			BusinessUtil.aLogger.info("Begin waiting...");
        	    			Iss = t_socket.getInputStream();
        	    			inBrs = new BufferedReader(new InputStreamReader(Iss,"UTF-8"));
        	    			strs = inBrs.readLine();
        	    			BusinessUtil.aLogger.info("Server said:"+strs);
        	    			testflag = false;
        	    		}
                        */
                    }else if (BusinessUtil.judge(jsonObject).equals(ClientCMDEnum.CMD.transnotificationcmd)){
                        BusinessUtil.aLogger.info("Request Type==="+ClientCMDEnum.CMD.transnotificationcmd);
                        //在TcpSocketList中设置已经接收到note信息的标记
                        tcb.setAutFlag(true);
                        //设定timeout，单位s
                        gpsUploadIntervalTime = 30*60;
                        
                        List<Map> noteList = new ArrayList<Map>();
                        JSONArray array = null;
                        boolean newest;String ID = null;
                        try{
                        	ID = jsonObject.getString("ID");
                        	//type 0 表示 message, 1 表示 order
                            type = Integer.parseInt(jsonObject.get("type").toString());
                            //True 代表此條訊息通知是新的提交. 若是false 則代表是client 閱讀了unread 資訊, Socket Server 遞送新的 badge 資訊給 client.
                            newest = jsonObject.getBoolean("newest");
                            array = JSONArray.fromObject(jsonObject.get("clients").toString());
                        }catch(Exception e){
                        	e.printStackTrace();
                        	String note = clientAddress+"发送的讯息不是规范的json格式，系统无法正常解析，中断本线程...";
                        	BusinessUtil.aLogger.info(note);
                        	exceptionPropCode = "E008";
                        	BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, exceptionPropCode,note);
                        	status = 0;
                        	BusinessUtil.sendMessage("retransnotificationcmd",status,exceptionPropCode,PS);
                        	break;
                        }
                        try{
                        	Object [] objectArray = array.toArray();
                            for(Object obj:objectArray){
                            	JSONObject jsonObjectItem = JSONObject.fromObject(obj);
                            	String uuid = jsonObjectItem.getString("uid");
                            	int badge = jsonObjectItem.getInt("badge");
                            	Map map = new HashMap();
                            	map.put("uid", uuid);
                            	map.put("badge", badge);
                            	noteList.add(map);
                            }
                        }catch(Exception e){
                        	e.printStackTrace();
                        	String note = clientAddress+"上传数据参数不符合要求，系统无法正常解析，中断本线程...";
                        	BusinessUtil.aLogger.info(note);
                        	exceptionPropCode = "E009";
                        	BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, exceptionPropCode,note);
                        	status = 0;
                        	BusinessUtil.sendMessage("retransnotificationcmd",status,exceptionPropCode,PS);
                        	break;
                        }
                        //return message to message server
                        BusinessUtil.sendMessage("retransnotificationcmd",status,exceptionPropCode,PS);
                        //send notification
                        BusinessUtil.sendNotification(ID,noteList, type,user_id, deviceType, clientAddress,newest);
                        break;
                    }else if(BusinessUtil.judge(jsonObject).equals(ClientCMDEnum.CMD.renotification)){
                        BusinessUtil.aLogger.info("Request Type==="+ClientCMDEnum.CMD.renotification);
                        String ID = null;int status = -1;String error = null;
                        try{
	                        ID = jsonObject.get("ID").toString();
	                        status = Integer.parseInt(jsonObject.get("status").toString());
	                        if(status!=1){
	                        	error = jsonObject.get("error").toString();
	                        }
                        }catch(Exception ex){
                        	exceptionPropCode = "E009";
                			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, exceptionPropCode,""+ex);
                        	BusinessUtil.aLogger.info(uuid+"gpsupload command解析出错:"+ex);
                        }
                        if (status==1){//it means success
                        	//设置收到回复讯息的标记
                            if (MobileServer.healthCheckList.containsKey(uuid)){
                            	HealthCheck _hc = MobileServer.healthCheckList.get(uuid);
                				List<NotificationMarkBean> notificationList = _hc.getNotificationList();
                				for(NotificationMarkBean bean:notificationList){
                					if (bean.getId().equals(ID)&&bean.isSendFlag()) {//存在此messageID和send 成功标记
                						bean.setReceiveFlag(true);
                						bean.setReceiveDate(new Date());
                					}
                				}
                            }
                        }else{//it means failure then log exception to db
                        	
                        }
                    }else if(BusinessUtil.judge(jsonObject).equals(ClientCMDEnum.CMD.bye)){
                    	BusinessUtil.aLogger.info("Request Type==="+ClientCMDEnum.CMD.bye);
                    	uuid = (String) jsonObject.get("uid");
                    	BusinessUtil.aLogger.info("接收到client发送正常中断指令，关闭本次连线...");
                    	break;
                    }else if(BusinessUtil.judge(jsonObject).equals(ClientCMDEnum.CMD.serverstatus)){
                    	StringBuffer returnStr = new StringBuffer();
                    	returnStr.append("<server>");
                    	/***********************begin to gather server information*****************************/
                    	returnStr.append("<ip>");returnStr.append(MobileServer.IP);returnStr.append("</ip>");
                    	returnStr.append("<port>");returnStr.append(MobileServer.PORT);returnStr.append("</port>");
                    	returnStr.append("<autAverageTime>");returnStr.append(BusinessUtil.getAverageAutTime());returnStr.append("</autAverageTime>");
                    	returnStr.append("<tcpSokcetOnlineConnection>");returnStr.append(MobileServer.outputStreams.size());returnStr.append("</tcpSokcetOnlineConnection>");
                    	returnStr.append("<tcpAvailableConnection>");returnStr.append(MobileServer.tcpSokcetMaxConnection-MobileServer.outputStreams.size());returnStr.append("</tcpAvailableConnection>");
                    	returnStr.append("<systemStartTime>");returnStr.append(Formatter.sdf.format(MobileServer.starttime));returnStr.append("</systemStartTime>");
                    	/*********************end to gather server information*******************************/
                    	returnStr.append("</server>");
                    	PS.println(returnStr.toString());
                    	break;
                    }else if(BusinessUtil.judge(jsonObject).equals(ClientCMDEnum.CMD.serverconfig)){
                    	StringBuffer returnStr = new StringBuffer();
                    	returnStr.append("<server>");
                    	/***********************begin to gather server information*****************************/
                    	returnStr.append("<ip>");returnStr.append(MobileServer.IP);returnStr.append("</ip>");
                    	returnStr.append("<port>");returnStr.append(MobileServer.PORT);returnStr.append("</port>");
                    	returnStr.append("<coordinatesBufferLength>");returnStr.append(MobileServer.coordinatesBufferLength);returnStr.append("</coordinatesBufferLength>");
                    	returnStr.append("<tcpSokcetMaxConnection>");returnStr.append(MobileServer.tcpSokcetMaxConnection);returnStr.append("</tcpSokcetMaxConnection>");
                    	/*returnStr.append("<blockNotificationServer>");
                    	returnStr.append("<ipBlock>");returnStr.append(MobileServer.notificationIpaddressBlock);returnStr.append("</ipBlock>");
                    	if(MobileServer.notificationIpaddressBlock){
                    		for(NotificationAcceptableIpaddress nai:MobileServer.ipaddress){
                    			returnStr.append("<ip>");returnStr.append(nai.getIpAddress());returnStr.append("</ip>");
                    		}
                    	}
                    	returnStr.append("</blockNotificationServer>");*/
                    	returnStr.append("<lockKeyWaitingCount>");returnStr.append(MobileServer.KEY_LOCK_WAITING_COUNT);returnStr.append("</lockKeyWaitingCount>");
                    	
                    	returnStr.append("<tcpSocketAutTimeout>");returnStr.append(MobileServer.tcpSocketAutTimeout);returnStr.append("</tcpSocketAutTimeout>");
                    	returnStr.append("<tcpSocketGpsuploadExpPacketCount>");returnStr.append(MobileServer.tcpSocketGpsuploadExpPacketCount);returnStr.append("</tcpSocketGpsuploadExpPacketCount>");
                    	returnStr.append("<tcpSocektGpsuploadHealthPolicyCount>");returnStr.append(MobileServer.tcpSocektGpsuploadHealthPolicyCount);returnStr.append("</tcpSocektGpsuploadHealthPolicyCount>");
                    	returnStr.append("<memcacheLockKeyLockCounts>");returnStr.append(MobileServer.memcacheLockKeyLockCounts);returnStr.append("</memcacheLockKeyLockCounts>");
                    	returnStr.append("<memcacheLockKeyWaitTime>");returnStr.append(MobileServer.memcacheLockKeyWaitTime);returnStr.append("</memcacheLockKeyWaitTime>");
                    	returnStr.append("<enableCheckGpsuploadExpPacket>");returnStr.append(MobileServer.enableCheckGpsuploadExpPacket);returnStr.append("</enableCheckGpsuploadExpPacket>");
                    	returnStr.append("<notificationToClientDelayTime>");returnStr.append(MobileServer.notificationToClientDelayTime);returnStr.append("</notificationToClientDelayTime>");
                    	returnStr.append("<notificationToClientResendTime>");returnStr.append(MobileServer.notificationToClientResendTime);returnStr.append("</notificationToClientResendTime>");
                    	returnStr.append("<ENCODING>");returnStr.append(MobileServer.ENCODING);returnStr.append("</ENCODING>");
                    	/*********************end to gather server information*******************************/
                    	returnStr.append("</server>");
                    	PS.println(returnStr.toString());
                    	break;
                    }else if(BusinessUtil.judge(jsonObject).equals(ClientCMDEnum.CMD.transgroupupdatecmd)){
                    	BusinessUtil.aLogger.info("Request Type==="+ClientCMDEnum.CMD.transgroupupdatecmd);
                    	JSONArray uuidArray = null;JSONArray useridArray = null;
                    	List<String> uuidlist = new ArrayList<String>();List<String> useridlist = new ArrayList<String>();
                    	try{
	                    	if(jsonObject.get("uuidclients")!=null){
	                    		uuidArray = JSONArray.fromObject(jsonObject.get("uuidclients").toString());
	                    		Object [] objectArray = uuidArray.toArray();
	                            for(Object obj:objectArray){
	                            	JSONObject jsonObjectItem = JSONObject.fromObject(obj);
	                            	String uuid = jsonObjectItem.getString("uid");
	                            	uuidlist.add(uuid);
	                            }
	                    	}
	                    	if(jsonObject.get("useridclients")!=null){
	                    		useridArray = JSONArray.fromObject(jsonObject.get("useridclients").toString());
	                    		Object [] objectArray = useridArray.toArray();
	                            for(Object obj:objectArray){
	                            	JSONObject jsonObjectItem = JSONObject.fromObject(obj);
	                            	String userid = jsonObjectItem.getString("userid");
	                            	useridlist.add(userid);
	                            }
	                    	}
                    	}catch(Exception e){
                        	e.printStackTrace();
                        	String note = clientAddress+"发送的讯息不是规范的json格式，系统无法正常解析，中断本线程...";
                        	BusinessUtil.aLogger.info(note);
                        	exceptionPropCode = "E008";
                        	BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, exceptionPropCode,note);
                        	status = 0;
                        	BusinessUtil.sendMessage("retransgroupupdatecmd",status,exceptionPropCode,PS);
                        	break;
                        }
                    	BusinessUtil.sendMessage("retransgroupupdatecmd",status,exceptionPropCode,PS);
                    	
                    	if(uuidlist.size()>0){
                    		for(String uuid:uuidlist){
                    			if(MobileServer.healthCheckList.containsKey(uuid)){//online
                    				updateMemcacheForUUID(uuid,DeviceConnectMode.beTracked);
                    			}
                    		}
                    	}
                    	if(useridlist.size()>0){
                    		for(String userid:useridlist){
                    			updateMemcacheForUSERID(userid,DeviceConnectMode.login);
                    		}
                    	}
                    	
                    }else if(BusinessUtil.judge(jsonObject).equals(ClientCMDEnum.CMD.transkillcmd)){
                    	BusinessUtil.aLogger.info("Request Type==="+ClientCMDEnum.CMD.transkillcmd);
                    	JSONArray uuidArray = null;JSONArray useridArray = null;
                    	List<String> uuidlist = new ArrayList<String>();List<String> useridlist = new ArrayList<String>();
                    	try{
	                    	if(jsonObject.get("uuidclients")!=null){
	                    		uuidArray = JSONArray.fromObject(jsonObject.get("uuidclients").toString());
	                    		Object [] objectArray = uuidArray.toArray();
	                            for(Object obj:objectArray){
	                            	JSONObject jsonObjectItem = JSONObject.fromObject(obj);
	                            	String uuid = jsonObjectItem.getString("uid");
	                            	uuidlist.add(uuid);
	                            }
	                    	}
	                    	if(jsonObject.get("useridclients")!=null){
	                    		useridArray = JSONArray.fromObject(jsonObject.get("useridclients").toString());
	                    		Object [] objectArray = useridArray.toArray();
	                            for(Object obj:objectArray){
	                            	JSONObject jsonObjectItem = JSONObject.fromObject(obj);
	                            	String userid = jsonObjectItem.getString("userid");
	                            	useridlist.add(userid);
	                            }
	                    	}
                    	}catch(Exception e){
                        	e.printStackTrace();
                        	String note = clientAddress+"发送的讯息不是规范的json格式，系统无法正常解析，中断本线程...";
                        	BusinessUtil.aLogger.info(note);
                        	exceptionPropCode = "E008";
                        	BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, exceptionPropCode,note);
                        	status = 0;
                        	BusinessUtil.sendMessage("rekillcmd",status,exceptionPropCode,PS);
                        	break;
                        }
                    	BusinessUtil.sendMessage("rekillcmd",status,exceptionPropCode,PS);
                    	
                    	if(uuidlist.size()>0){
                    		for(String uuid:uuidlist){
                    			HealthCheck _hc = MobileServer.healthCheckList.get(uuid);
                    			if(MobileServer.healthCheckList.containsKey(uuid)){//online
                    				//向被覆盖的thread发送aut error讯息
                                	if (MobileServer.outputStreams.containsKey(uuid)){
                                		BusinessUtil.sendMessage("aut",0,"E014",MobileServer.outputStreams.get(uuid));
                                	}
                                	BusinessUtil.afterCloseSocketDone(MobileServer.healthCheckList.get(uuid).getMobileServerThreadObj());
                    				//中断指定device的连线
                                	_hc.breakConnectionDone();//终止前uuid对应的MobileServerThread thread
                                	_hc.stopThread();//终止前uuid对应的health check thread
                                }
                    		}
                    	}
                    	if(useridlist.size()>0){
                    		for(String userid:useridlist){
                    			for(Iterator it = MobileServer.healthCheckList.keySet().iterator();it.hasNext(); )   {
                    				String tt_uuid = (String)it.next();
                    				HealthCheck t_hc = MobileServer.healthCheckList.get(tt_uuid);
                    				if(t_hc.getMobileServerThreadObj().user_id==Integer.parseInt(userid)){
                    					//向被覆盖的thread发送aut error讯息
                                    	if (MobileServer.outputStreams.containsKey(tt_uuid)){
                                    		BusinessUtil.sendMessage("aut",0,"E014",MobileServer.outputStreams.get(tt_uuid));
                                    	}
                                    	BusinessUtil.afterCloseSocketDone(t_hc.getMobileServerThreadObj());
                    					//中断指定device的连线
                                    	t_hc.breakConnectionDone();//终止前uuid对应的MobileServerThread thread
                                    	t_hc.stopThread();//终止前uuid对应的health check thread
                                    	break;
                    				}
                    			}
                    		}
                    	}
                    	
                    }
                    
                }else{
                	break;
                }
                
            }
            
        }catch (SocketException ex) {
            BusinessUtil.aLogger.info("uuid:"+uuid+" ERROR:"+ex);
        }catch(IOException e){
            BusinessUtil.aLogger.info("uuid:"+uuid+" ERROR:"+e);
        }finally{
            try {
                if (!socket.isClosed()) socket.close();
                Is.close();
                inBr.close();
                if (!this.isExeCloseSocketDone) BusinessUtil.afterCloseSocketDone(this);
            } catch (IOException e) {
                e.printStackTrace();
            }
            BusinessUtil.aLogger.info(uuid+"线程已经结束.....");
        }
    }
    
    private void updateMemcacheForUSERID(String user_id,DeviceConnectMode mode) {
    	this.uuid = MobileServer.useridUuidList.get(user_id).toString();
    	if(this.uuid==null||"".equals(this.uuid)){
    		BusinessUtil.aLogger.info("user_id:"+user_id+"并不在线，无法执行updateMemcacheForUSERID.....");
    		return;
    	}
    	//get groupid and taskid from memcache by uuid
    	String[] former_groupid = (String [])MobileServer.uuidGroupList.get(this.uuid);
    	String[] former_taskid = (String [])MobileServer.uuidTaskList.get(this.uuid);
    	
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			db = DBConnection.getConnection("gpsdata");
			String sql = null;
			if(MobileServer.enableMultiLoginMode){//集合uuid和userid查询到的groupid与taskid之和
				
			}else{
				sql = " SELECT df.group_id type_id, d.user_id, js.uuid, 'G' type"+
				" FROM ( jos_mt_device_friends as df INNER JOIN jos_mt_device as d ON df.befriend_uuid = d.uuid)"+
				" LEFT JOIN jos_session as js ON d.user_id = js.userid  AND js.uuid <> ''"+
				" WHERE df.request_time <> df.accept_time"+
				" AND df.status = 1"+
				" AND df.befriend_uuid = "+user_id+
				" UNION"+
				" SELECT gd.group_id type_id, d.user_id, js.uuid, 'G' type"+
				" FROM (jos_mt_group_device as gd INNER JOIN jos_mt_device as d ON gd.uuid = d.uuid)"+
				" LEFT JOIN jos_session as js ON d.user_id = js.userid AND js.uuid <> ''"+
				" WHERE d.uuid = "+user_id+
				" UNION"+
				" SELECT tm.task_id type_id, d.user_id, js.uuid, 'T' type"+
				" FROM (jos_mt_task_member as tm INNER JOIN jos_mt_device as d ON tm.uuid = d.uuid)"+
				" LEFT JOIN jos_session as js ON  d.user_id = js.userid AND js.uuid <> ''"+
				" WHERE  tm.uuid = "+user_id+
				" AND tm.status = 1 ";
			}
	        BusinessUtil.aLogger.info("sql==="+sql);
	        ps = db.prepareStatement(sql);
	        rs = ps.executeQuery();
	        int g_count=0;
        	int t_count=0;
	        while(rs.next()){
	        	String type = rs.getString("type");
	        	if (type.equalsIgnoreCase("G")){//groupId
	        		g_count++;
	        	}else if(type.equalsIgnoreCase("T")){//taskId
	        		t_count++;
	        	}
	        }
	        if (g_count>0){
	            groupId = new String[g_count];
	        }
	        if (t_count>0){
	        	taskId = new String[t_count];
	        }
	        g_count=0;
        	t_count=0;
	        rs.beforeFirst();
	        while(rs.next()){
	        	String type = rs.getString("type");
	        	if (type.equalsIgnoreCase("G")){//groupId
	        		String g_id = String.valueOf(rs.getInt("type_id"));
	        		groupId[g_count] = g_id;
	        		g_count++;
	        	}else if(type.equalsIgnoreCase("T")){//taskId
	        		String t_id = String.valueOf(rs.getInt("type_id"));
	        		taskId[t_count] = t_id;
	        		t_count++;
	        	}
	        	//uuid = rs.getString("uuid");
	        }
	        if(null!=rs) rs.close();
	        ps.close();
	        db.close();
	        
	        //compare group and check group
	        List<String> add_groupId = new ArrayList<String>();
	        List<String> del_groupId = new ArrayList<String>();
	        for(String former_gid:former_groupid){
	        	boolean flag = true;
	        	for(String gid:groupId){
	        		if(former_gid.equals(gid)){
	        			flag = false;
	        		}
	        	}
	        	if(flag){//need to delete
	        		del_groupId.add(former_gid);
	        	}
	        }
	        for(String gid:groupId){
	        	boolean flag = true;
	        	for(String former_gid:former_groupid){
	        		if(former_gid.equals(gid)){
	        			flag = false;
	        		}
	        	}
	        	if(flag){//need to add
	        		add_groupId.add(gid);
	        	}
	        }
	        if(del_groupId.size()>0){
	        	String[] new_del_groupId = new String[del_groupId.size()];
	        	for(int i=0;i<del_groupId.size();i++){
	        		new_del_groupId[i] = (String)del_groupId.get(i);
	        	}
	        	delGroup(this.uuid, Integer.parseInt(user_id),new_del_groupId, mode);
	        }
	        if(add_groupId.size()>0){
	        	String[] new_add_groupId = new String[add_groupId.size()];
	        	for(int i=0;i<add_groupId.size();i++){
	        		new_add_groupId[i] = (String)add_groupId.get(i);
	        	}
	        	checkGroup(this.uuid, Integer.parseInt(user_id),new_add_groupId, mode);
	        }
	        //compare task and check task
	        List<String> add_taskId = new ArrayList<String>();
	        List<String> del_taskId = new ArrayList<String>();
	        for(String former_tid:former_taskid){
	        	boolean flag = true;
	        	for(String tid:taskId){
	        		if(former_tid.equals(tid)){
	        			flag = false;
	        		}
	        	}
	        	if(flag){//need to delete
	        		del_taskId.add(former_tid);
	        	}
	        }
	        for(String tid:taskId){
	        	boolean flag = true;
	        	for(String former_tid:former_taskid){
	        		if(former_tid.equals(tid)){
	        			flag = false;
	        		}
	        	}
	        	if(flag){//need to add
	        		add_taskId.add(tid);
	        	}
	        }
	        if(del_taskId.size()>0){
	        	String[] new_del_taskId = new String[del_taskId.size()];
	        	for(int i=0;i<del_taskId.size();i++){
	        		new_del_taskId[i] = (String)del_taskId.get(i);
	        	}
	        	delTask(this.uuid, Integer.parseInt(user_id),new_del_taskId, mode);
	        }
	        if(add_taskId.size()>0){
	        	String[] new_add_taskId = new String[add_taskId.size()];
	        	for(int i=0;i<add_taskId.size();i++){
	        		new_add_taskId[i] = (String)add_taskId.get(i);
	        	}
	        	checkTask(this.uuid, Integer.parseInt(user_id),new_add_taskId, mode);
	        }
	        
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (PropertyVetoException e) {
			e.printStackTrace();
		}
	}
    
	private void delTask(String p_uuid, int user_id, String[] taskId,DeviceConnectMode mode) {
    	if(taskId==null||taskId.length==0){
    		BusinessUtil.aLogger.info("当前taskId为空，不能执行checkTask");
    		return;
    	}
    	String uuid = mode.equals(DeviceConnectMode.beTracked)?p_uuid:user_id+"_"+p_uuid;
        //first generate memcache client object
        BusinessUtil.aLogger.info("开始根据taskId查询memcache...");
        try{
        for(String tid:taskId){
        	BusinessUtil.aLogger.info("当前taskId:"+"T"+tid);
        	
        	int temp_count = 0;
        	boolean exist_flag = false;
    		while(temp_count<=MobileServer.memcacheLockKeyLockCounts){//其他线程在操作此item
    			if(MemcacheUtil.getMemCachedClient().get(PREFIX_LOCK+"T"+tid)!=null){
    				BusinessUtil.inc();//统计总数加1
    				temp_count++;
    				try {
						Thread.sleep(MobileServer.memcacheLockKeyWaitTime);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
    			}else{
    				exist_flag = true;//解锁
    				break;
    			}
    		}
    		temp_count = 0;
    		if (!exist_flag){//始终无法等待解锁
    			String note = "function delTask中访问memcache失败，始终无法等待解锁，发生异常.....";
        		BusinessUtil.aLogger.info(note);
        		//log to db
    			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
        	}else{
        		boolean add_flag = MemcacheUtil.getMemCachedClient().add(PREFIX_LOCK+"T"+tid,(int) MEMCACHE_LOCKKEY_EXPIRATION,uuid);//add lock
        		if (add_flag){//add 成功
        			String uuidstr = (String) MemcacheUtil.getMemCachedClient().get("T"+tid);
                    String[] newuuidItem = null;
                    if (uuidstr!=null){
                    	BusinessUtil.aLogger.info("T"+tid+"对应的value:"+uuidstr);
                        boolean flag = false;
                        String[] uuidItem = BusinessUtil.StringToArray(uuidstr,",");
                        int index = 0;
                        for(int i=0;i<uuidItem.length;i++){
                            if (uuidItem[i].equals(uuid)){
                                flag = true;
                                index = i;
                            }
                        }
                        if (flag){
                        	BusinessUtil.aLogger.info("T"+tid+"未包含"+uuid+"，开始添加"+uuid+"到"+"T"+tid+"对应的value中...");
                            newuuidItem = (String [])BusinessUtil.removeArrayItem(uuidItem, index);
                            newuuidItem[0] = String.valueOf(newuuidItem.length-1);
                            MemcacheUtil.getMemCachedClient().set("T"+tid, 0,BusinessUtil.ArrayToString(newuuidItem));
                            BusinessUtil.aLogger.info("完成添加"+uuid+"到"+"T"+tid+"对应的value中...");
                        }
                    }
                    //删除lock，如果不成功尝试WAIT_UNLOCK_TIME次
            		boolean remove_flag = false;
            		while(temp_count<=MobileServer.memcacheLockKeyLockCounts){
            			boolean del_flag = MemcacheUtil.getMemCachedClient().delete(PREFIX_LOCK+"T"+tid);//remove lock
            			if (!del_flag){
                			temp_count++;
                			try {
        						Thread.sleep(MobileServer.memcacheLockKeyWaitTime);
        					} catch (InterruptedException e) {
        						e.printStackTrace();
        					}
                		}else{
                			remove_flag = true;
                			break;
                		}
            		}
            		if (!remove_flag){//删除失败
            			String note = "function delTask中访问memcache失败，删除失败，发生异常.....";
            			BusinessUtil.aLogger.info(note);
                		//log to db
            			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
            		}
        		}else{
        			String note = "function delTask中访问memcache失败，add lock key失败，发生异常.....";
        			BusinessUtil.aLogger.info(note);
            		//log to db
        			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
        		}
        	}
        }
        mem_error = true;
        }catch(MemcachedException e){
        	String note = "function delTask中访问memcache失败....."+e;
        	if(mem_error){
        		BusinessUtil.aLogger.error(note);
        		mem_error = false;
        	}
			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
        } catch (TimeoutException e) {
        	String note = "function delTask中访问memcache失败....."+e;
        	if(mem_error){
        		BusinessUtil.aLogger.error(note);
        		mem_error = false;
        	}
			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
		} catch (InterruptedException e) {//ignore
			e.printStackTrace();
		}
    }

	private void delGroup(String p_uuid, int user_id, String[] groupId,
			DeviceConnectMode mode) {
    	if(groupId==null||groupId.length==0){
    		BusinessUtil.aLogger.info("当前groupId为空，不能执行delGroup");
    		return;
    	}
    	String uuid = mode.equals(DeviceConnectMode.beTracked)?p_uuid:user_id+"_"+p_uuid;
        //first generate memcache client object
        BusinessUtil.aLogger.info("开始根据groupId查询memcache...");
        try{
        for(String gid:groupId){
        	BusinessUtil.aLogger.info("当前groupId:"+"G"+gid);
        	
        	int temp_count = 0;
        	boolean exist_flag = false;
    		while(temp_count<=MobileServer.memcacheLockKeyLockCounts){//其他线程在操作此item
    			if(MemcacheUtil.getMemCachedClient().get(PREFIX_LOCK+"G"+gid)!=null){
    				BusinessUtil.inc();//统计总数加1
    				temp_count++;
    				try {
						Thread.sleep(MobileServer.memcacheLockKeyWaitTime);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
    			}else{
    				exist_flag = true;//解锁
    				break;
    			}
    		}
    		temp_count = 0;
    		if (!exist_flag){//始终无法等待解锁
    			String note = "function checkGroup中访问memcache失败，始终无法等待解锁，发生异常.....";
        		BusinessUtil.aLogger.info(note);
        		//log to db
    			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
        	}else{
        		boolean add_flag = MemcacheUtil.getMemCachedClient().add(PREFIX_LOCK+"G"+gid,(int) MEMCACHE_LOCKKEY_EXPIRATION,uuid);//add lock
        		if (add_flag){//add 成功
        			String uuidstr = (String) MemcacheUtil.getMemCachedClient().get("G"+gid);
                    String[] newuuidItem = null;
                    if (uuidstr!=null){
                    	BusinessUtil.aLogger.info("G"+gid+"对应的value:"+uuidstr);
                        boolean flag = false;
                        String[] uuidItem = BusinessUtil.StringToArray(uuidstr,",");
                        int index=0;
                        for(int i=0;i<uuidItem.length;i++){
                            if (uuidItem[i].equals(uuid)){
                                flag = true;
                                index = i;
                            }
                        }
                        if (flag){
                            newuuidItem = (String [])BusinessUtil.removeArrayItem(uuidItem, index);
                            newuuidItem[0] = String.valueOf(newuuidItem.length-1);
                            MemcacheUtil.getMemCachedClient().set("G"+gid, 0,BusinessUtil.ArrayToString(newuuidItem));
                            BusinessUtil.aLogger.info("完成删除"+uuid+"到"+"G"+gid+"对应的value中...");
                        }
                    }
                    //删除lock，如果不成功尝试WAIT_UNLOCK_TIME次
            		boolean remove_flag = false;
            		while(temp_count<=MobileServer.memcacheLockKeyLockCounts){
            			boolean del_flag = MemcacheUtil.getMemCachedClient().delete(PREFIX_LOCK+"G"+gid);//remove lock
            			if (!del_flag){
                			temp_count++;
                			try {
        						Thread.sleep(MobileServer.memcacheLockKeyWaitTime);
        					} catch (InterruptedException e) {
        						e.printStackTrace();
        					}
                		}else{
                			remove_flag = true;
                			break;
                		}
            		}
            		if (!remove_flag){//删除失败
            			String note = "function delGroup中访问memcache失败，删除失败，发生异常.....";
            			BusinessUtil.aLogger.info(note);
                		//log to db
            			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
            		}
        		}else{
        			String note = "function delGroup中访问memcache失败，add lock key失败，发生异常.....";
        			BusinessUtil.aLogger.info(note);
            		//log to db
        			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
        		}
        	}
        }
        mem_error = true;
        }catch(MemcachedException e){
        	String note = "function checkGroup中访问memcache失败....."+e;
        	if(mem_error){
        		BusinessUtil.aLogger.error(note);
        		mem_error = false;
        	}
			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
        } catch (TimeoutException e) {
        	String note = "function checkGroup中访问memcache失败....."+e;
        	if(mem_error){
        		BusinessUtil.aLogger.error(note);
        		mem_error = false;
        	}
			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
		} catch (InterruptedException e) {//ignore
			e.printStackTrace();
		}
    }

	private void updateMemcacheForUUID(String uuid,DeviceConnectMode mode) {
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			db = DBConnection.getConnection("gpsdata");
			String sql = " SELECT df.group_id type_id, d.user_id, 'G' type"+
							" FROM jos_mt_device_friends df, jos_mt_device d"+
							" WHERE df.befriend_uuid = d.uuid"+
							" AND df.request_time <> df.accept_time"+
							" AND df.status = '1'"+
							" AND df.befriend_uuid = '"+uuid+"'"+
							" UNION"+
							" SELECT gd.group_id type_id, d.user_id, 'G' type"+
							" FROM jos_mt_group_device gd, jos_mt_device d"+
							" WHERE gd.uuid = d.uuid"+
							" AND d.uuid = '"+uuid+"'"+
							" UNION"+
							" SELECT tm.task_id type_id, d.user_id, 'T' type"+
							" FROM jos_mt_task_member tm, jos_mt_device d"+
							" WHERE tm.uuid = d.uuid"+
							" AND tm.uuid = '"+uuid+"'"+
							" AND tm.status = '1' ";
	        BusinessUtil.aLogger.info("sql==="+sql);
	        ps = db.prepareStatement(sql);
	        rs = ps.executeQuery();
	        int g_count=0;
        	int t_count=0;
	        while(rs.next()){
	        	String type = rs.getString("type");
	        	if (type.equalsIgnoreCase("G")){//groupId
	        		g_count++;
	        	}else if(type.equalsIgnoreCase("T")){//taskId
	        		t_count++;
	        	}
	        }
	        if (g_count>0){
	            groupId = new String[g_count];
	        }
	        if (t_count>0){
	        	taskId = new String[t_count];
	        }
	        g_count=0;
        	t_count=0;
	        rs.beforeFirst();
	        while(rs.next()){
	        	String type = rs.getString("type");
	        	if (type.equalsIgnoreCase("G")){//groupId
	        		String g_id = String.valueOf(rs.getInt("type_id"));
	        		groupId[g_count] = g_id;
	        		g_count++;
	        	}else if(type.equalsIgnoreCase("T")){//taskId
	        		String t_id = String.valueOf(rs.getInt("type_id"));
	        		taskId[t_count] = t_id;
	        		t_count++;
	        	}
	        	this.user_id = rs.getInt("user_id");
	        }
	        if(null!=rs) rs.close();
	        ps.close();
	        db.close();
	        checkGroup(uuid, this.user_id,groupId, mode);
	        checkTask(uuid, this.user_id,taskId, mode);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (PropertyVetoException e) {
			e.printStackTrace();
		}
	}

	/**
     * 当authentication successfully之后，check 当前online count，如果达到threshold，则error信息发送mail并log db
     */
    private void checkOnlineCountThreshold() {
    	if(server.tcpSokcetMaxConnection*server.onlineCountThreshold==server.outputStreams.size()){
    		BusinessUtil.aLogger.error(server.SERVER_SN+"在"+Formatter.db2_sdf.format(new Date())+"记录的在线client数量:"+server.outputStreams.size()+
					",已经达到警戒值"+server.tcpSokcetMaxConnection*server.onlineCountThreshold);
    		CheckOnlineCount.setOnlineCount(server);
		}
	}

	public void stopThread() {
        this._run = false;
    }
    
    
    /**
     * 根据uuid查询device在系统中是否有注册过并返回groupId和user_id
     * @throws Exception
     */
    public void autByDB(){
    	//begin check UUID
        try {
        	ResultSet rs = null;ResultSet rs1 =null;
	        db = DBConnection.getConnection("aut");
	        String sql = " SELECT uuid, userid FROM jos_session WHERE session_id = '"+auttoken+"'";
	        BusinessUtil.aLogger.info("sql==="+sql);
	        PreparedStatement ps = db.prepareStatement(sql);
	        rs = ps.executeQuery();
	        String t_uuid = null;
	        while(rs.next()){
	        	user_id = rs.getInt("userid");
	        	t_uuid = rs.getString("uuid");
	        	count+=1;
	        }
	        if(count==1&&t_uuid.equals(uuid)){
	        	if(user_id==0){
	        		mode = DeviceConnectMode.beTracked;
	        	}else if(user_id!=0&&user_id!=-1){
	        		mode = DeviceConnectMode.login;
	        	}
	        	count = 0;
	        	String s_sql = null;
		        if(mode.equals(DeviceConnectMode.beTracked)){
		        	s_sql = " SELECT df.group_id type_id, d.user_id, 'G' type"+
		        			" FROM jos_mt_device_friends df, jos_mt_device d"+
		        			" WHERE df.befriend_uuid = d.uuid"+
		        			" AND df.request_time <> df.accept_time"+
		        			" AND df.status = '1'"+
		        			" AND df.befriend_uuid = '"+uuid+"'"+
		        			" UNION"+
		        			" SELECT gd.group_id type_id, d.user_id, 'G' type"+
		        			" FROM jos_mt_group_device gd, jos_mt_device d"+
		        			" WHERE gd.uuid = d.uuid"+
		        			" AND d.uuid = '"+uuid+"'"+
		        			" UNION"+
		        			" SELECT tm.task_id type_id, d.user_id, 'T' type"+
		        			" FROM jos_mt_task_member tm, jos_mt_device d"+
		        			" WHERE tm.uuid = d.uuid"+
		        			" AND tm.uuid = '"+uuid+"'"+
		        			" AND tm.status = '1' ";
		        	BusinessUtil.aLogger.info("sql==="+s_sql);
			        ps = db.prepareStatement(s_sql);
			        rs1 = ps.executeQuery();
			        int g_count=0;
		        	int t_count=0;
			        while(rs1.next()){
			        	String type = rs1.getString("type");
			        	if (type.equalsIgnoreCase("G")){//groupId
			        		g_count++;
			        	}else if(type.equalsIgnoreCase("T")){//taskId
			        		t_count++;
			        	}
			        	this.ref_userId = rs1.getInt("user_id");
			        }
			        if (g_count>0){
			            groupId = new String[g_count];
			        }
			        if (t_count>0){
			        	taskId = new String[t_count];
			        }
			        g_count=0;
		        	t_count=0;
		        	rs1.beforeFirst();
			        while(rs1.next()){
			        	String type = rs1.getString("type");
			        	if (type.equalsIgnoreCase("G")){//groupId
			        		String g_id = String.valueOf(rs1.getInt("type_id"));
			        		groupId[g_count] = g_id;
			        		g_count++;
			        	}else if(type.equalsIgnoreCase("T")){//taskId
			        		String t_id = String.valueOf(rs1.getInt("type_id"));
			        		taskId[t_count] = t_id;
			        		t_count++;
			        	}
			        }
		        }
		        if(mode.equals(DeviceConnectMode.login)){
		        	if (MobileServer.enableMultiLoginMode){
		        		s_sql = " SELECT df.group_id type_id, d.user_id, js.uuid, 'G' TYPE "+
		        		" FROM ( jos_mt_device_friends AS df INNER JOIN jos_mt_device AS d ON df.befriend_uuid = d.uuid) "+
		        		" LEFT JOIN jos_session AS js ON d.user_id = js.userid  AND js.uuid <> '' "+
		        		" WHERE df.request_time <> df.accept_time "+
		        		" AND df.status = 1 AND df.befriend_uuid = "+user_id+
		        		" UNION "+
		        		" SELECT gd.group_id type_id, d.user_id, js.uuid, 'G' TYPE "+
		        		" FROM (jos_mt_group_device AS gd INNER JOIN jos_mt_device AS d ON gd.uuid = d.uuid) "+
		        		" LEFT JOIN jos_session AS js ON d.user_id = js.userid AND js.uuid <> '' "+
		        		" WHERE d.uuid = "+user_id+
		        		" UNION "+
		        		" SELECT tm.task_id type_id, d.user_id, js.uuid, 'T' TYPE "+
		        		" FROM (jos_mt_task_member AS tm INNER JOIN jos_mt_device AS d ON tm.uuid = d.uuid) "+
		        		" LEFT JOIN jos_session AS js ON  d.user_id = js.userid AND js.uuid <> '' "+
		        		" WHERE AND tm.status = 1 and tm.uuid = "+user_id+
		        		" UNION "+
		        		" SELECT df.group_id type_id, d.user_id, d.uuid ,'G' TYPE "+
		        		" FROM jos_mt_device_friends df, jos_mt_device d "+
		        		" WHERE df.befriend_uuid = d.uuid "+
		        		" AND df.request_time <> df.accept_time "+
		        		" AND df.status = '1' AND df.befriend_uuid = '"+uuid+"'"+
		        		" UNION "+
		        		" SELECT gd.group_id type_id, d.user_id, d.uuid ,'G' TYPE "+
		        		" FROM jos_mt_group_device gd, jos_mt_device d "+
		        		" WHERE gd.uuid = d.uuid "+
		        		" AND d.uuid = '"+uuid+"'"+
		        		" UNION "+
		        		" SELECT tm.task_id type_id, d.user_id, d.uuid ,'T' TYPE "+
		        		" FROM jos_mt_task_member tm, jos_mt_device d "+
		        		" WHERE tm.uuid = d.uuid "+
		        		" AND tm.uuid = '"+uuid+"' AND tm.status = '1' ";
		        	}else{
		        		s_sql = " SELECT df.group_id type_id, d.user_id, js.uuid, 'G' type"+
		    			" FROM ( jos_mt_device_friends as df INNER JOIN jos_mt_device as d ON df.befriend_uuid = d.uuid)"+
		    			" LEFT JOIN jos_session as js ON d.user_id = js.userid  AND js.uuid <> ''"+
		    			" WHERE df.request_time <> df.accept_time"+
		    			" AND df.status = 1"+
		    			" AND df.befriend_uuid = "+user_id+
		    			" UNION"+
		    			" SELECT gd.group_id type_id, d.user_id, js.uuid, 'G' type"+
		    			" FROM (jos_mt_group_device as gd INNER JOIN jos_mt_device as d ON gd.uuid = d.uuid)"+
		    			" LEFT JOIN jos_session as js ON d.user_id = js.userid AND js.uuid <> ''"+
		    			" WHERE d.uuid = "+user_id+
		    			" UNION"+
		    			" SELECT tm.task_id type_id, d.user_id, js.uuid, 'T' type"+
		    			" FROM (jos_mt_task_member as tm INNER JOIN jos_mt_device as d ON tm.uuid = d.uuid)"+
		    			" LEFT JOIN jos_session as js ON  d.user_id = js.userid AND js.uuid <> ''"+
		    			" WHERE  tm.uuid = "+user_id+
		    			" AND tm.status = 1 ";
		        		BusinessUtil.aLogger.info("sql==="+s_sql);
				        ps = db.prepareStatement(s_sql);
				        rs1 = ps.executeQuery();
				        int g_count=0;
			        	int t_count=0;
				        while(rs1.next()){
				        	String type = rs1.getString("type");
				        	if (type.equalsIgnoreCase("G")){//groupId
				        		g_count++;
				        	}else if(type.equalsIgnoreCase("T")){//taskId
				        		t_count++;
				        	}
				        	this.ref_uuid = rs1.getString("uuid");
				        }
				        if (g_count>0){
				            groupId = new String[g_count];
				        }
				        if (t_count>0){
				        	taskId = new String[t_count];
				        }
				        g_count=0;
			        	t_count=0;
			        	rs1.beforeFirst();
				        while(rs1.next()){
				        	String type = rs1.getString("type");
				        	if (type.equalsIgnoreCase("G")){//groupId
				        		String g_id = String.valueOf(rs1.getInt("type_id"));
				        		groupId[g_count] = g_id;
				        		g_count++;
				        	}else if(type.equalsIgnoreCase("T")){//taskId
				        		String t_id = String.valueOf(rs1.getInt("type_id"));
				        		taskId[t_count] = t_id;
				        		t_count++;
				        	}
				        }
		        	}
		        }
		        
	        }else{
	        	autFlag = true;
	        }
	        
	        if(null!=rs) rs.close();
	        if(null!=rs1) rs1.close();
	        ps.close();
	        db.close();
	        sql_error = true;
		} catch (SQLException e) {
			if(sql_error){//防止多个client重复log error信息和mail
				BusinessUtil.aLogger.error("autByDB:"+e);
				sql_error = false;
			}
			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E004",""+e);
		} catch (PropertyVetoException e) {
			e.printStackTrace();
		}
    }
    
    /**
     * 遍历memcache中的key为groupId元素的item，如果有uuid，则删除并重新set，清除uuid关联该groupId的在线信息，如果没有则不做任何操作
     * @param uuid
     * @param groupId
     */
    public void removeDeviceFromGroup(String p_uuid,int userId,String[] groupId,DeviceConnectMode mode){
        if (p_uuid==null||p_uuid.equals("")){
            return;
        }
        if (groupId==null||groupId.length==0){
            return;
        }
        String uuid = mode.equals(DeviceConnectMode.beTracked)?p_uuid:userId+"_"+p_uuid;
        try{
        for (int i=0;i<groupId.length;i++){
        	int temp_count = 0;
        	boolean exist_flag = false;
    		while(temp_count<=MobileServer.memcacheLockKeyLockCounts){//其他线程在操作此item
    			if(MemcacheUtil.getMemCachedClient().get(PREFIX_LOCK+"G"+groupId[i])!=null){
    				BusinessUtil.inc();//统计总数加1
    				temp_count++;
    				try {
						Thread.sleep(MobileServer.memcacheLockKeyWaitTime);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
    			}else{
    				exist_flag = true;//解锁
    				break;
    			}
    		}
    		temp_count = 0;
        	if (!exist_flag){//始终无法等待解锁
        		String note = "function removeDeviceFromGroup中访问memcache失败，始终无法等待解锁，发生异常.....";
        		BusinessUtil.aLogger.info(note);
        		//log to db
    			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
        	}else{
        		boolean add_flag = MemcacheUtil.getMemCachedClient().add(PREFIX_LOCK+"G"+groupId[i],(int) MEMCACHE_LOCKKEY_EXPIRATION,uuid);//add lock
        		if (add_flag){//add 成功
        			String value = (String)MemcacheUtil.getMemCachedClient().get("G"+groupId[i]);
        			String [] temp = BusinessUtil.StringToArray(value,",");
        			if (temp!=null){
        				int index = Integer.parseInt(temp[0]);
        				if(mode.equals(DeviceConnectMode.login)&&MobileServer.enableMultiLoginMode){
        					//TBD
        				}else{
        					for (int j=0;j<temp.length;j++){
            					if (temp[j].equals(uuid)){
            						if (index==1){//只有一个元素，删除之后则没有，所以直接删除整个groupId item
            							MemcacheUtil.getMemCachedClient().delete("G"+groupId[i]);
            							BusinessUtil.aLogger.info("完成在memcache中删除key为"+"G"+groupId[i]+"的item...");
            							break;
            						}else{
            							String[] temp1 = BusinessUtil.removeArrayItem(temp,j);
            							temp1[0] = String.valueOf(index-1);
                						MemcacheUtil.getMemCachedClient().set("G"+groupId[i], 0,BusinessUtil.ArrayToString(temp1));
                						BusinessUtil.aLogger.info("完成在memcache中删除key为"+"G"+groupId[i]+"的item中"+uuid+"...");
                						break;
            						}
            					}
            				}
        				}
        			}
        			//删除lock，如果不成功尝试WAIT_UNLOCK_TIME次
            		boolean remove_flag = false;
            		while(temp_count<=MobileServer.memcacheLockKeyLockCounts){
            			boolean del_flag = MemcacheUtil.getMemCachedClient().delete(PREFIX_LOCK+"G"+groupId[i]);//remove lock
            			if (!del_flag){
                			temp_count++;
                			try {
        						Thread.sleep(MobileServer.memcacheLockKeyWaitTime);
        					} catch (InterruptedException e) {
        						e.printStackTrace();
        					}
                		}else{
                			remove_flag = true;
                			break;
                		}
            		}
            		if (!remove_flag){//删除失败
            			String note = "function removeDeviceFromGroup中访问memcache失败，删除失败，发生异常.....";
            			BusinessUtil.aLogger.info(note);
                		//log to db
            			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
            		}
        		}else{
        			String note = "function removeDeviceFromGroup中在"+"G"+groupId[i]+"中删除"+uuid+",访问memcache失败，发生异常.....";
        			BusinessUtil.aLogger.info(note);
            		//log to db
        			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
        		}
        	}
        }
        mem_error = true;
        }catch(MemcachedException e){
        	String note = "function removeDeviceFromGroup中访问memcache失败....."+e;
        	if (mem_error){
        		BusinessUtil.aLogger.error(note);
        		mem_error = false;
        	}
			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
        } catch (TimeoutException e) {
        	String note = "function removeDeviceFromGroup中访问memcache失败....."+e;
        	if (mem_error){
        		BusinessUtil.aLogger.error(note);
        		mem_error = false;
        	}
			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
		} catch (InterruptedException e) {//ignore
			e.printStackTrace();
		}
    }
    
    /**
     * 遍历memcache中的key为taskId元素的item，如果有uuid，则删除并重新set，清除uuid关联该taskId的在线信息，如果没有则不做任何操作
     * @param uuid
     * @param taskId
     */
    public void removeDeviceFromTask(String p_uuid,int userId,String[] taskId,DeviceConnectMode mode){
        if (p_uuid==null||p_uuid.equals("")){
            return;
        }
        if (taskId==null||taskId.length==0){
            return;
        }
        String uuid = mode.equals(DeviceConnectMode.beTracked)?p_uuid:userId+"_"+p_uuid;
        try{
        for (int i=0;i<taskId.length;i++){
        	int temp_count = 0;
        	boolean exist_flag = false;
    		while(temp_count<=MobileServer.memcacheLockKeyLockCounts){//其他线程在操作此item
    			if(MemcacheUtil.getMemCachedClient().get(PREFIX_LOCK+"T"+taskId[i])!=null){
    				BusinessUtil.inc();//统计总数加1
    				temp_count++;
    				try {
						Thread.sleep(MobileServer.memcacheLockKeyWaitTime);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
    			}else{
    				exist_flag = true;//解锁
    				break;
    			}
    		}
    		temp_count = 0;
        	if (!exist_flag){//始终无法等待解锁
        		String note = "function removeDeviceFromTask中访问memcache失败，始终无法等待解锁，发生异常.....";
        		BusinessUtil.aLogger.info(note);
        		//log to db
    			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
        	}else{
        		boolean add_flag = MemcacheUtil.getMemCachedClient().add(PREFIX_LOCK+"T"+taskId[i],(int)MEMCACHE_LOCKKEY_EXPIRATION,uuid);//add lock
        		if (add_flag){//add 成功
        			String value = (String)MemcacheUtil.getMemCachedClient().get("T"+taskId[i]);
        			String [] temp = BusinessUtil.StringToArray(value,",");
        			if (temp!=null){
        				int index = Integer.parseInt(temp[0]);
        				if(mode.equals(DeviceConnectMode.login)&&MobileServer.enableMultiLoginMode){
        					//TBD
        				}else{
        					for (int j=0;j<temp.length;j++){
            					if (temp[j].equals(uuid)){
            						if (index==1){//只有一个元素，删除之后则没有，所以直接删除整个groupId item
            							MemcacheUtil.getMemCachedClient().delete("T"+taskId[i]);
            							BusinessUtil.aLogger.info("完成在memcache中删除key为"+"T"+taskId[i]+"的item...");
            							break;
            						}else{
            							String[] temp1 = BusinessUtil.removeArrayItem(temp,j);
            							temp1[0] = String.valueOf(index-1);
                						MemcacheUtil.getMemCachedClient().set("T"+taskId[i],0, BusinessUtil.ArrayToString(temp1));
                						BusinessUtil.aLogger.info("完成在memcache中删除key为"+"T"+taskId[i]+"的item中"+uuid+"...");
                						break;
            						}
            					}
            				}
        				}
        				
        			}
        			//删除lock，如果不成功尝试WAIT_UNLOCK_TIME次
            		boolean remove_flag = false;
            		while(temp_count<=MobileServer.memcacheLockKeyLockCounts){
            			boolean del_flag = MemcacheUtil.getMemCachedClient().delete(PREFIX_LOCK+"T"+taskId[i]);//remove lock
            			if (!del_flag){
                			temp_count++;
                			try {
        						Thread.sleep(MobileServer.memcacheLockKeyWaitTime);
        					} catch (InterruptedException e) {
        						e.printStackTrace();
        					}
                		}else{
                			remove_flag = true;
                			break;
                		}
            		}
            		if (!remove_flag){//删除失败
            			String note = "function removeDeviceFromTask中访问memcache失败，删除失败，发生异常.....";
            			BusinessUtil.aLogger.info(note);
            			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
            		}
        		}else{
        			String note = "function removeDeviceFromTask中在"+"T"+taskId[i]+"中删除"+uuid+",访问memcache失败，发生异常.....";
        			BusinessUtil.aLogger.info(note);
        			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
        		}
        	}
        }
        mem_error = true;
        }catch(MemcachedException e){
        	String note = "function removeDeviceFromTask中访问memcache失败....."+e;
        	if (mem_error){
        		BusinessUtil.aLogger.error(note);
        		mem_error = false;
        	}
			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
        } catch (TimeoutException e) {
        	String note = "function removeDeviceFromTask中访问memcache失败....."+e;
        	if (mem_error){
        		BusinessUtil.aLogger.error(note);
        		mem_error = false;
        	}
			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
		} catch (InterruptedException e) {//ignore
			e.printStackTrace();
		}
    }
    
    /**
     * 从cache中查找key为UUID的item是否存在，如果存在则插入UUID，不存在则创建item
     * @param uuid
     * @param deviceType
     * @param coordinates
     * @param speed
     * @param date
     */
    public boolean checkAndUploadCoordinates(String uuid,int user_id,int deviceType,
    		String [] coordinates,double speed,String date){
    	String tag = mode.equals(DeviceConnectMode.beTracked)?"U"+uuid:user_id+"_"+uuid;
    	//是否需要终止当前线程的标记
    	boolean isShut = false;
    	/***开始check interval内的上传data频率，如果频率超过设定频率则需要保存数据并终止线程****/
    	int arraylength = intervalBufferArray.length;
    	int nullindex=-1;
    	if (MobileServer.enableCheckGpsuploadExpPacket){
        	//check intervalBufferArray[i]内是否有为空的元素，如果有则填充为当前data的时间，如果没有则将数组元素依次提前，最后一个元素设置为当前data的时间
        	for(int i=0;i<arraylength;i++){
        		if (intervalBufferArray[i]==null){
        			nullindex = i;
        			break;
        		}
        	}
        	if(nullindex!=-1){//数组中还有空元素，不需要check
        		intervalBufferArray[nullindex]=Formatter.sdf.format(new Date());
        	}else{
        		for(int i=0;i<arraylength-1;i++){
        			intervalBufferArray[i] = intervalBufferArray[i+1];
        		}
        		intervalBufferArray[arraylength-1]=Formatter.sdf.format(new Date());
        		//begin check
        		try {
    				long difftime = Formatter.sdf.parse(intervalBufferArray[arraylength-1]).getTime()-Formatter.sdf.parse(intervalBufferArray[0]).getTime();
    				BusinessUtil.aLogger.info("each upload difftime=="+difftime/1000);
    				if (difftime<=interval*1000){
    					isShut = true;
    				}
    			} catch (ParseException e) {
    				e.printStackTrace();
    			}
        	}
    	}
    	/***完成check interval内的上传data频率****/
    	if (isShut){//interrupt thread now
    		String note = tag+"的device在"+interval+"s内有"+arraylength+"笔记录超过规定upload频率，保存数据，终止线程...";
        	BusinessUtil.afterCloseSocketDone(this);
        	BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E003",note);
        	BusinessUtil.aLogger.info(note);
        	return false;
        }
    	try{
        //向memchace中存入gps data
    	int temp_count = 0;
    	boolean exist_flag = false;
		while(temp_count<=MobileServer.memcacheLockKeyLockCounts){//其他线程在操作此item
			if(MemcacheUtil.getMemCachedClient().get(PREFIX_LOCK+tag)!=null){
				BusinessUtil.inc();//统计总数加1
				temp_count++;
				try {
					Thread.sleep(MobileServer.memcacheLockKeyWaitTime);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}else{
				exist_flag = true;//解锁
				break;
			}
		}
		temp_count = 0;
    	if (!exist_flag){//始终无法等待解锁
    		String note = "添加key为"+tag+"的item失败...";
    		BusinessUtil.aLogger.info(note);
    		//log to db
			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
    	}else{
    		boolean add_flag = MemcacheUtil.getMemCachedClient().add(PREFIX_LOCK+tag,(int) MEMCACHE_LOCKKEY_EXPIRATION,uuid);//add lock
    		if (add_flag){//add 成功
    			String value = (String)MemcacheUtil.getMemCachedClient().get(tag);
    			String[] result = BusinessUtil.StringToArray(value,",");
                String [] item = null;
                if (result==null){
                    //加入以UUID为key的item,
                    //item格式为Index, Position buffer 1, Position buffer 2, ... , Position buffer N
                    item = new String[]{"1",coordinates[0]+"#"+coordinates[1]+"#"+coordinates[2]+"#"+speed+"#"+date};
                    BusinessUtil.aLogger.info("Memcache中没有key为"+tag+"的item,开始添加...");
                    MemcacheUtil.getMemCachedClient().set(tag, 0,BusinessUtil.ArrayToString(item));
                    BusinessUtil.aLogger.info("完成添加key为"+tag+"的item...");
                }else{
                	int index = Integer.parseInt(result[0]);
                    if (index==MobileServer.coordinatesBufferLength){//达到指定长度上限，于是save到DB，然后重新添加新的坐标信息记录
                    	BusinessUtil.saveDB(result, uuid, user_id, deviceType,clientAddress);
                        item = new String[]{"1",coordinates[0]+"#"+coordinates[1]+"#"+coordinates[2]+"#"+speed+"#"+date};
                        BusinessUtil.aLogger.info("Memcache中key为"+tag+"的item达到指定长度上限，先save到DB，然后重新添加新的坐标信息记录...");
                        MemcacheUtil.getMemCachedClient().set(tag,0,BusinessUtil.ArrayToString(item));
                		BusinessUtil.aLogger.info("完成添加key为"+tag+"的item...");
                    }else{//还未达到上限，继续添加新的坐标信息记录 3
                    	BusinessUtil.aLogger.info("Memcache中key为"+tag+"的item还未达到上限，继续添加新的坐标信息记录...");
                        item = new String[index+2];
                        item[0] = String.valueOf(index+1);
                        for (int j=0;j<index;j++){
                            String itemvalue = result[j+1];
                            item[j+1] = itemvalue;
                        }
                        item[index+1] = coordinates[0]+"#"+coordinates[1]+"#"+coordinates[2]+"#"+speed+"#"+date;
                        BusinessUtil.aLogger.info("开始上传"+tag+"到Memcache...");
                        MemcacheUtil.getMemCachedClient().set(tag,0,BusinessUtil.ArrayToString(item));
                        BusinessUtil.aLogger.info("完成添加key为"+tag+"的item...");
                    }
                }
                //删除lock，如果不成功尝试WAIT_UNLOCK_TIME次
        		boolean remove_flag = false;
        		while(temp_count<=MobileServer.memcacheLockKeyLockCounts){
        			boolean del_flag = MemcacheUtil.getMemCachedClient().delete(PREFIX_LOCK+tag);//remove lock
        			if (!del_flag){
            			temp_count++;
            			try {
    						Thread.sleep(MobileServer.memcacheLockKeyWaitTime);
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
            		}else{
            			remove_flag = true;
            			break;
            		}
        		}
        		if (!remove_flag){//删除失败
        			String note = "function checkAndUploadCoordinates中访问memcache失败，删除失败，发生异常.....";
        			BusinessUtil.aLogger.info(note);
        			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
        		}
    		}else{
    			String note = "添加key为"+tag+"的item失败...";
    			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
            	BusinessUtil.aLogger.info(note);
    		}
    	}
    	mem_error = true;
    	}catch(MemcachedException e){
        	String note = "function checkAndUploadCoordinates中访问memcache失败....."+e;
        	if (mem_error){
        		BusinessUtil.aLogger.error(note);
        		mem_error = false;
        	}
			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
        } catch (TimeoutException e) {
        	String note = "function checkAndUploadCoordinates中访问memcache失败....."+e;
        	if (mem_error){
        		BusinessUtil.aLogger.error(note);
        		mem_error = false;
        	}
			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
		} catch (InterruptedException e) {//ignore
			e.printStackTrace();
		}
        return true;
    }
    
    /**
     * 从cache中查找groupID是否存在，如果存在则在groupid的item中插入UUID，不存在则创建以groupid为key的item
     * item是以逗号分隔的字符串，第一个元素为count
     * @param uuid
     * @param groupId
     */
    private void checkGroup(String p_uuid, int user_id,String[] groupId,DeviceConnectMode mode)
    {
    	if(groupId==null||groupId.length==0){
    		BusinessUtil.aLogger.info("当前groupId为空，不能执行checkGroup");
    		return;
    	}
    	String uuid = mode.equals(DeviceConnectMode.beTracked)?p_uuid:user_id+"_"+p_uuid;
        //first generate memcache client object
        BusinessUtil.aLogger.info("开始根据groupId查询memcache...");
        try{
        for(String gid:groupId){
        	BusinessUtil.aLogger.info("当前groupId:"+"G"+gid);
        	
        	int temp_count = 0;
        	boolean exist_flag = false;
    		while(temp_count<=MobileServer.memcacheLockKeyLockCounts){//其他线程在操作此item
    			if(MemcacheUtil.getMemCachedClient().get(PREFIX_LOCK+"G"+gid)!=null){
    				BusinessUtil.inc();//统计总数加1
    				temp_count++;
    				try {
						Thread.sleep(MobileServer.memcacheLockKeyWaitTime);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
    			}else{
    				exist_flag = true;//解锁
    				break;
    			}
    		}
    		temp_count = 0;
    		if (!exist_flag){//始终无法等待解锁
    			String note = "function checkGroup中访问memcache失败，始终无法等待解锁，发生异常.....";
        		BusinessUtil.aLogger.info(note);
        		//log to db
    			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
        	}else{
        		boolean add_flag = MemcacheUtil.getMemCachedClient().add(PREFIX_LOCK+"G"+gid,(int) MEMCACHE_LOCKKEY_EXPIRATION,uuid);//add lock
        		if (add_flag){//add 成功
        			String uuidstr = (String) MemcacheUtil.getMemCachedClient().get("G"+gid);
                    String[] newuuidItem = null;
                    if (uuidstr!=null){
                    	BusinessUtil.aLogger.info("G"+gid+"对应的value:"+uuidstr);
                        boolean flag = false;
                        String[] uuidItem = BusinessUtil.StringToArray(uuidstr,",");
                        for(String uid:uuidItem){
                            if (uid.equals(uuid)){
                                flag = true;
                            }
                        }
                        if (!flag){
                        	BusinessUtil.aLogger.info("G"+gid+"未包含"+uuid+"，开始添加"+uuid+"到"+"G"+gid+"对应的value中...");
                            newuuidItem = (String [])BusinessUtil.arrayAddLength(uuidItem, 1);
                            newuuidItem[0] = String.valueOf(newuuidItem.length-1);
                        	if(mode.equals(DeviceConnectMode.login)&&MobileServer.enableMultiLoginMode){
                        		//TBD
                        	}else{
                        		newuuidItem[newuuidItem.length-1] = uuid;
                        	}
                            MemcacheUtil.getMemCachedClient().set("G"+gid, 0,BusinessUtil.ArrayToString(newuuidItem));
                            BusinessUtil.aLogger.info("完成添加"+uuid+"到"+"G"+gid+"对应的value中...");
                        }
                    }else{
                    	BusinessUtil.aLogger.info("Memcache中未包含"+"G"+gid+",开始添加...");
                        newuuidItem = new String[2];
                        newuuidItem[0] = "1";
                    	if(mode.equals(DeviceConnectMode.login)&&MobileServer.enableMultiLoginMode){
                    		//TBD
                    	}else{
                    		newuuidItem[1] = uuid;
                    	}
                        MemcacheUtil.getMemCachedClient().set("G"+gid, 0,BusinessUtil.ArrayToString(newuuidItem));
                        BusinessUtil.aLogger.info("完成添加"+"G"+gid+"...");
                    }
                    //删除lock，如果不成功尝试WAIT_UNLOCK_TIME次
            		boolean remove_flag = false;
            		while(temp_count<=MobileServer.memcacheLockKeyLockCounts){
            			boolean del_flag = MemcacheUtil.getMemCachedClient().delete(PREFIX_LOCK+"G"+gid);//remove lock
            			if (!del_flag){
                			temp_count++;
                			try {
        						Thread.sleep(MobileServer.memcacheLockKeyWaitTime);
        					} catch (InterruptedException e) {
        						e.printStackTrace();
        					}
                		}else{
                			remove_flag = true;
                			break;
                		}
            		}
            		if (!remove_flag){//删除失败
            			String note = "function checkGroup中访问memcache失败，删除失败，发生异常.....";
            			BusinessUtil.aLogger.info(note);
                		//log to db
            			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
            		}
        		}else{
        			String note = "function checkGroup中访问memcache失败，add lock key失败，发生异常.....";
        			BusinessUtil.aLogger.info(note);
            		//log to db
        			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
        		}
        	}
        }
        mem_error = true;
        }catch(MemcachedException e){
        	String note = "function checkGroup中访问memcache失败....."+e;
        	if(mem_error){
        		BusinessUtil.aLogger.error(note);
        		mem_error = false;
        	}
			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
        } catch (TimeoutException e) {
        	String note = "function checkGroup中访问memcache失败....."+e;
        	if(mem_error){
        		BusinessUtil.aLogger.error(note);
        		mem_error = false;
        	}
			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
		} catch (InterruptedException e) {//ignore
			e.printStackTrace();
		}
    }
    
    /**
     * 从cache中查找taskID是否存在，如果存在则在taskid的item中插入UUID，不存在则创建以taskid为key的item
     * item是以逗号分隔的字符串，第一个元素为count
     * @param uuid
     * @param taskId
     */
    private void checkTask(String p_uuid,int user_id, String[] taskId,DeviceConnectMode mode)
    {
    	if(taskId==null||taskId.length==0){
    		BusinessUtil.aLogger.info("当前taskId为空，不能执行checkTask");
    		return;
    	}
    	String uuid = mode.equals(DeviceConnectMode.beTracked)?p_uuid:user_id+"_"+p_uuid;
        //first generate memcache client object
        BusinessUtil.aLogger.info("开始根据taskId查询memcache...");
        try{
        for(String tid:taskId){
        	BusinessUtil.aLogger.info("当前taskId:"+"T"+tid);
        	
        	int temp_count = 0;
        	boolean exist_flag = false;
    		while(temp_count<=MobileServer.memcacheLockKeyLockCounts){//其他线程在操作此item
    			if(MemcacheUtil.getMemCachedClient().get(PREFIX_LOCK+"T"+tid)!=null){
    				BusinessUtil.inc();//统计总数加1
    				temp_count++;
    				try {
						Thread.sleep(MobileServer.memcacheLockKeyWaitTime);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
    			}else{
    				exist_flag = true;//解锁
    				break;
    			}
    		}
    		temp_count = 0;
    		if (!exist_flag){//始终无法等待解锁
    			String note = "function checkTask中访问memcache失败，始终无法等待解锁，发生异常.....";
        		BusinessUtil.aLogger.info(note);
        		//log to db
    			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
        	}else{
        		boolean add_flag = MemcacheUtil.getMemCachedClient().add(PREFIX_LOCK+"T"+tid,(int) MEMCACHE_LOCKKEY_EXPIRATION,uuid);//add lock
        		if (add_flag){//add 成功
        			String uuidstr = (String) MemcacheUtil.getMemCachedClient().get("T"+tid);
                    String[] newuuidItem = null;
                    if (uuidstr!=null){
                    	BusinessUtil.aLogger.info("T"+tid+"对应的value:"+uuidstr);
                        boolean flag = false;
                        String[] uuidItem = BusinessUtil.StringToArray(uuidstr,",");
                        for(String uid:uuidItem){
                            if (uid.equals(uuid)){
                                flag = true;
                            }
                        }
                        if (!flag){
                        	BusinessUtil.aLogger.info("T"+tid+"未包含"+uuid+"，开始添加"+uuid+"到"+"T"+tid+"对应的value中...");
                            newuuidItem = (String [])BusinessUtil.arrayAddLength(uuidItem, 1);
                            newuuidItem[0] = String.valueOf(newuuidItem.length-1);
                        	if(mode.equals(DeviceConnectMode.login)&&MobileServer.enableMultiLoginMode){
                        		//TBD
                        	}else{
                        		newuuidItem[newuuidItem.length-1] = uuid;
                        	}
                            MemcacheUtil.getMemCachedClient().set("T"+tid, 0,BusinessUtil.ArrayToString(newuuidItem));
                            BusinessUtil.aLogger.info("完成添加"+uuid+"到"+"T"+tid+"对应的value中...");
                        }
                    }else{
                    	BusinessUtil.aLogger.info("Memcache中未包含"+"T"+tid+",开始添加...");
                        newuuidItem = new String[2];
                        newuuidItem[0] = "1";
                    	if(mode.equals(DeviceConnectMode.login)&&MobileServer.enableMultiLoginMode){
                    		//TBD
                    	}else{
                    		newuuidItem[1] = uuid;
                    	}
                        MemcacheUtil.getMemCachedClient().set("T"+tid, 0,BusinessUtil.ArrayToString(newuuidItem));
                        BusinessUtil.aLogger.info("完成添加"+"T"+tid+"...");
                    }
                    //删除lock，如果不成功尝试WAIT_UNLOCK_TIME次
            		boolean remove_flag = false;
            		while(temp_count<=MobileServer.memcacheLockKeyLockCounts){
            			boolean del_flag = MemcacheUtil.getMemCachedClient().delete(PREFIX_LOCK+"T"+tid);//remove lock
            			if (!del_flag){
                			temp_count++;
                			try {
        						Thread.sleep(MobileServer.memcacheLockKeyWaitTime);
        					} catch (InterruptedException e) {
        						e.printStackTrace();
        					}
                		}else{
                			remove_flag = true;
                			break;
                		}
            		}
            		if (!remove_flag){//删除失败
            			String note = "function checkTask中访问memcache失败，删除失败，发生异常.....";
            			BusinessUtil.aLogger.info(note);
                		//log to db
            			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
            		}
        		}else{
        			String note = "function checkTask中访问memcache失败，add lock key失败，发生异常.....";
        			BusinessUtil.aLogger.info(note);
            		//log to db
        			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
        		}
        	}
        }
        mem_error = true;
        }catch(MemcachedException e){
        	String note = "function checkTask中访问memcache失败....."+e;
        	if(mem_error){
        		BusinessUtil.aLogger.error(note);
        		mem_error = false;
        	}
			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
        } catch (TimeoutException e) {
        	String note = "function checkTask中访问memcache失败....."+e;
        	if(mem_error){
        		BusinessUtil.aLogger.error(note);
        		mem_error = false;
        	}
			BusinessUtil.logException(uuid, user_id, deviceType, clientAddress, "E011",note);
		} catch (InterruptedException e) {//ignore
			e.printStackTrace();
		}
    }
    
    public static void main(String args[]){
        /*String time = "aa,bb,cc";
        String[] array = time.split(",");
        Class type = array.getClass();
        BusinessUtil.aLogger.info(type.isArray());*/
    	String s = "{\"cmd\":\"aut\", \"uid\":\"7c6d6203b015\", \"dev_type\":1}";
    	JSONObject jsonObject = null;
    	jsonObject = JSONObject.fromObject(s);
    	Integer.parseInt(jsonObject.get("interval").toString());
    	BusinessUtil.aLogger.info(jsonObject.get("interval"));
    	
    }
    
}  
